/*
 * Powered By dico
 * Since 2017 - 2018
 */
package com.seeyoui.kensite.bussiness.orderlang.warehouseProduct.controller;

import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.seeyoui.kensite.common.util.DateUtils;
import com.seeyoui.kensite.common.util.StringUtils;
import com.seeyoui.kensite.common.constants.StringConstant;
import com.seeyoui.kensite.common.exception.CRUDException;
import com.seeyoui.kensite.common.exception.Exceptions;
import com.seeyoui.kensite.common.base.domain.EasyUIDataGrid;
import com.seeyoui.kensite.common.base.controller.BaseController;
import com.seeyoui.kensite.common.util.RequestResponseUtil;
import com.seeyoui.kensite.common.util.excel.ExportExcel;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.lucene.index.Term;
import org.apache.shiro.authz.annotation.RequiresPermissions;

import com.seeyoui.kensite.common.base.domain.Page;
import com.seeyoui.kensite.framework.luence.domain.LuceneDocument;
import com.seeyoui.kensite.framework.luence.util.LuceneUtils;
import com.seeyoui.kensite.framework.system.domain.SysUser;
import com.seeyoui.kensite.framework.system.util.UserUtils;
import com.seeyoui.kensite.bussiness.orderlang.delivery.domain.Delivery;
import com.seeyoui.kensite.bussiness.orderlang.delivery.service.DeliveryService;
import com.seeyoui.kensite.bussiness.orderlang.deliveryProduct.domain.DeliveryProduct;
import com.seeyoui.kensite.bussiness.orderlang.deliveryProduct.service.DeliveryProductService;
import com.seeyoui.kensite.bussiness.orderlang.inbound.domain.Inbound;
import com.seeyoui.kensite.bussiness.orderlang.inbound.service.InboundService;
import com.seeyoui.kensite.bussiness.orderlang.inboundProduct.domain.InboundProduct;
import com.seeyoui.kensite.bussiness.orderlang.inboundProduct.service.InboundProductService;
import com.seeyoui.kensite.bussiness.orderlang.outbound.domain.Outbound;
import com.seeyoui.kensite.bussiness.orderlang.outbound.domain.OutboundVO;
import com.seeyoui.kensite.bussiness.orderlang.outbound.service.OutboundService;
import com.seeyoui.kensite.bussiness.orderlang.outboundProduct.domain.OutboundProduct;
import com.seeyoui.kensite.bussiness.orderlang.outboundProduct.service.OutboundProductService;
import com.seeyoui.kensite.bussiness.orderlang.product.domain.Product;
import com.seeyoui.kensite.bussiness.orderlang.productAttachment.domain.ProductAttachment;
import com.seeyoui.kensite.bussiness.orderlang.productAttachment.service.ProductAttachmentService;
import com.seeyoui.kensite.bussiness.orderlang.productBrand.domain.ProductBrand;
import com.seeyoui.kensite.bussiness.orderlang.productBrand.service.ProductBrandService;
import com.seeyoui.kensite.bussiness.orderlang.productCategory.domain.ProductCategory;
import com.seeyoui.kensite.bussiness.orderlang.productCategory.service.ProductCategoryService;
import com.seeyoui.kensite.bussiness.orderlang.productSpec.domain.ProductSpec;
import com.seeyoui.kensite.bussiness.orderlang.productSpec.service.ProductSpecService;
import com.seeyoui.kensite.bussiness.orderlang.productUnit.domain.ProductUnit;
import com.seeyoui.kensite.bussiness.orderlang.productUnit.service.ProductUnitService;
import com.seeyoui.kensite.bussiness.orderlang.warehouseProduct.domain.WarehouseProduct;
import com.seeyoui.kensite.bussiness.orderlang.warehouseProduct.domain.WarehouseProductVO;
import com.seeyoui.kensite.bussiness.orderlang.warehouseProduct.service.WarehouseProductService;
import com.sun.star.uno.RuntimeException;

/**
 * WarehouseProduct
 * 
 * @author dico
 * @version 2.0
 * @since 1.0
 * @date 2018-02-07
 */

@Controller
@RequestMapping(value = "warehouse/warehouseProduct")
public class WarehouseProductController extends BaseController {

    @Autowired
    private WarehouseProductService warehouseProductService;
    @Autowired
    private InboundService inboundService;
    @Autowired
    private InboundProductService inboundProductSerive;
    @Autowired
    private ProductBrandService productBrandService;
    @Autowired
    private DeliveryService deliveryService;
    @Autowired
    private DeliveryProductService deliveryProductService;
    @Autowired
    private OutboundService outboundService;
    @Autowired
    private ProductCategoryService productCategoryService;
    @Autowired
    private OutboundProductService outboundProductService;
    @Autowired
    private ProductAttachmentService productAttachmentService;
    @Autowired
    private ProductSpecService productSpecService;
    @Autowired
    private ProductUnitService productUnitService;

    /**
     * 获取商品库存
     * 
     * @param modelMap
     * @param warehouseProduct
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/findProductInvertory", method = RequestMethod.POST)
    @ResponseBody
    public Object findProductInvertory(HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap,
            String productId, String productPriceId, String productSpecId) throws Exception {
        Map map = new HashMap();
        map.put("productId", productId);
        map.put("productPriceId", productPriceId);
        String[] productSpecIds = productSpecId.split(",");
        List productSpecIdList = new ArrayList();
        for (int i = 0; i < productSpecIds.length; i++) {
            productSpecIdList.add(productSpecIds[i]);
        }
        map.put("productSpecIdList", productSpecIdList);
        List<WarehouseProduct> warehouseProductList = warehouseProductService.findProductInvertory(map);
        EasyUIDataGrid eudg = new EasyUIDataGrid();
        eudg.setRows(warehouseProductList);
        return eudg;
    }

    /**
     * 展示列表页面
     * 
     * @param modelMap
     * @param module
     * @return
     * @throws Exception
     */
    // @RequiresPermissions("warehouse:warehouseProduct:view")
    @RequestMapping(value = "/{page}")
    public ModelAndView view(HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap,
            @PathVariable String page) throws Exception {
        return new ModelAndView("bussiness/orderlang/warehouseProduct/" + page, modelMap);
    }

    /**
     * 根据ID查询单条数据
     * 
     * @param modelMap
     * @param module
     * @return
     * @throws Exception
     */
    // @RequiresPermissions("warehouse:warehouseProduct:select")
    @RequestMapping(value = "/data/{id}")
    @ResponseBody
    public Object data(HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap, @PathVariable String id)
            throws Exception {
        WarehouseProduct warehouseProduct = warehouseProductService.findOne(id);
        return warehouseProduct;
    }

    /**
     * 根据ID查询单条数据并返回相应表单
     * 
     * @param modelMap
     * @param module
     * @return
     * @throws Exception
     */
    // @RequiresPermissions("warehouse:warehouseProduct:view")
    @RequestMapping(value = "/form/{page}/{id}")
    public ModelAndView form(HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap,
            @PathVariable String page, @PathVariable String id) throws Exception {
        WarehouseProduct warehouseProduct = warehouseProductService.findOne(id);
        modelMap.put("warehouseProduct", warehouseProduct);
        return new ModelAndView("bussiness/orderlang/warehouseProduct/" + page, modelMap);
    }

    /**
     * 获取列表展示数据
     * 
     * @param modelMap
     * @param warehouseProduct
     * @return
     * @throws Exception
     */
    // @RequiresPermissions("warehouse:warehouseProduct:select")
    @RequestMapping(value = "/list/data", method = RequestMethod.POST)
    @ResponseBody
    public Object listData(HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap,
            WarehouseProduct warehouseProduct) throws Exception {
        List<WarehouseProduct> warehouseProductList = warehouseProductService.findList(warehouseProduct);
        int total = warehouseProductService.findTotal(warehouseProduct);
        EasyUIDataGrid eudg = new EasyUIDataGrid();
        eudg.setTotal(String.valueOf(total));
        eudg.setRows(warehouseProductList);
        return eudg;
    }

    /**
     * 获取列表展示数据带分页器用于jsp自己做分页
     * 
     * @param modelMap
     * @param warehouseProduct
     * @return
     * @throws Exception
     */
    // @RequiresPermissions("warehouse:warehouseProduct:view")
    @RequestMapping(value = "/list/page", method = RequestMethod.POST)
    @ResponseBody
    public Object listPage(HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap, int page, int rows,
            String productName, String warehouseId, String categoryId, String isRelease, WarehouseProduct warehouseProduct) throws Exception {
        Map map = new HashMap();
        map.put("productName", productName);
        map.put("warehouseId", warehouseId);
        map.put("categoryId", categoryId);
        map.put("isRelease", isRelease);
        map.put("row", warehouseProduct.getRow());
        map.put("rows", rows);
        List<Product> productList = warehouseProductService.findListForInventory(map);
        for (Product product : productList) {
            ProductBrand productBrand = productBrandService.findOne(product.getBrandId());
            if (null != productBrand) {
                product.setBrandId(productBrand.getBrandName());
            } else {
                product.setBrandId("");
            }
        }
        int total = warehouseProductService.findTotalForInventory(map);
        Page<WarehouseProduct> pageInfo = new Page<WarehouseProduct>(page, rows, total);
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("rows", productList);
        dataMap.put("page", pageInfo);
        return dataMap;
    }

    /**
     * 获取库存列表信息
     * 
     * @param modelMap
     * @param warehouseProduct
     * @return
     * @throws Exception
     */
    // @RequiresPermissions("warehouse:warehouseProduct:view")
    @RequestMapping(value = "/findWarehousProduct", method = RequestMethod.POST)
    @ResponseBody
    public Object findWarehousProduct(HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap, int page,
            int rows, String productName, String warehouseId, String categoryId, String isRelease, WarehouseProduct warehouseProduct) throws Exception {
        String level = "";
        List<String> categoryIdList = null;
        if(!StringUtils.isEmpty(categoryId)){
            String[] str = categoryId.split(",");
            categoryId = str[0];
            level = str[1];
            categoryIdList = new ArrayList<String>();
            // 查询当前分类下所有商品分类的ID
            queryCategoryId(categoryIdList, categoryId);
        }
        
        Map map = new HashMap();
        map.put("productName", productName);
        map.put("warehouseId", warehouseId);
        map.put("categoryIdList", categoryIdList);
        map.put("isRelease", isRelease);
        map.put("row", warehouseProduct.getRow());
        map.put("rows", rows);
        List<WarehouseProductVO> warehouseProductVOList = warehouseProductService.findWarehousProduct(map);
        for (WarehouseProductVO warehouseProductVO : warehouseProductVOList) {
            String imgId = warehouseProductVO.getProductImgUrl();
            // 查询图片地址
            ProductAttachment productAttachment = new ProductAttachment();
            productAttachment.setProductId(imgId);
            productAttachment.setType("0");
            productAttachment.setSeq("0");
            List<ProductAttachment> productAttachmentList = productAttachmentService.findList(productAttachment);
            if (null != productAttachmentList && productAttachmentList.size() >= 0) {
                warehouseProductVO.setProductImgUrl(productAttachmentList.get(0).getUrl());
            }
            // 查询规格
            String productPriceId = warehouseProductVO.getProductPriceId();
            if (!StringUtils.isEmpty(productPriceId)) {
                ProductSpec queryProductSpec = new ProductSpec();
                queryProductSpec.setProductPriceId(productPriceId);
                List<ProductSpec> productSpecList = productSpecService.findList(queryProductSpec);
                String specValue = "";
                for (ProductSpec productSpec : productSpecList) {
                    specValue += "," + productSpec.getSpecName() + " : " + productSpec.getSpecValue();
                }
                if (!StringUtils.isEmpty(specValue)) {
                    warehouseProductVO.setProductPriceId(specValue.substring(1));
                } else {
                    warehouseProductVO.setProductPriceId("");
                }
            }
            // 查询单位
            String bigUnitId = warehouseProductVO.getBigUnitName();
            String littleUnitId = warehouseProductVO.getLittleUnitName();
            if (!StringUtils.isEmpty(bigUnitId)) {
                ProductUnit productUnit = productUnitService.findOne(bigUnitId);
                if (null != productUnit && !"".equals(productUnit.getUnitName())) {
                    warehouseProductVO.setBigUnitName(productUnit.getUnitName());
                } else {
                    warehouseProductVO.setBigUnitName("");
                }
            }
            if (!StringUtils.isEmpty(littleUnitId)) {
                ProductUnit productUnit = productUnitService.findOne(littleUnitId);
                if (null != productUnit) {
                    warehouseProductVO.setLittleUnitName(productUnit.getUnitName());
                } else {
                    warehouseProductVO.setLittleUnitName("");
                }
            }
            if (!StringUtils.isEmpty(warehouseProductVO.getBigUnitName()) && !StringUtils.isEmpty(warehouseProductVO.getLittleUnitName())) {
                warehouseProductVO.setBigUnitName(warehouseProductVO.getBigUnitName() + "/");
            }
        }
        int total = warehouseProductService.findTotalWarehousProduct(map);
        Page<WarehouseProduct> pageInfo = new Page<WarehouseProduct>(page, rows, total);
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("rows", warehouseProductVOList);
        dataMap.put("page", pageInfo);
        return dataMap;
    }
    
    /**
     * 递归查询当前ID下所有商品分类的ID
     * @param strList
     * @param categoryId
     */
    private void queryCategoryId(List<String> strList,String categoryId){
        strList.add(categoryId);
        ProductCategory queryProductCategory = new ProductCategory();
        queryProductCategory.setParentId(categoryId);
        queryProductCategory.setDelFlag("0");
        List<ProductCategory> productCategoryList = productCategoryService.findList(queryProductCategory);
        for (ProductCategory productCategory : productCategoryList) {
            queryCategoryId(strList, productCategory.getId());
        }
    }

    /**
     * 获取所有数据
     * 
     * @param modelMap
     * @param warehouseProduct
     * @return
     * @throws Exception
     */
    // @RequiresPermissions("warehouse:warehouseProduct:select")
    @RequestMapping(value = "/list/all", method = RequestMethod.POST)
    @ResponseBody
    public Object listAll(HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap,
            WarehouseProduct warehouseProduct) throws Exception {
        List<WarehouseProduct> warehouseProductList = warehouseProductService.findAll(warehouseProduct);
        return warehouseProductList;
    }

    /**
     * 保存新增的数据
     * 
     * @param modelMap
     * @param warehouseProduct
     * @return
     * @throws Exception
     */
    // @RequiresPermissions("warehouse:warehouseProduct:insert")
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public String save(HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap,
            WarehouseProduct warehouseProduct) throws Exception {
        if (!beanValidator(modelMap, warehouseProduct)) {
            RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE);
            return null;
        }
        warehouseProductService.save(warehouseProduct);
        RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
        return null;
    }

    /**
     * 商品入库的方法
     * 
     * @param modelMap
     * @param warehouseProduct
     * @return
     * @throws Exception
     */
    @Transactional
    @RequestMapping(value = "/productStorage", method = RequestMethod.POST)
    @ResponseBody
    public String productStorage(HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap,
            String warehouseProductStrs) throws Exception {
        warehouseProductStrs = StringEscapeUtils.unescapeHtml(warehouseProductStrs);// 去除字符串中的乱码字符
        JSONArray warehouseProductJson = JSON.parseArray(warehouseProductStrs);// 将字符串转换为JSON对象数组
        Iterator warehouseProductIterator = warehouseProductJson.iterator();
        List<WarehouseProduct> addWarehouseProductList = new ArrayList<WarehouseProduct>();
        List<WarehouseProduct> updateWarehouseProductList = new ArrayList<WarehouseProduct>();
        // 解析json对象数组
        List<String> quantityList = new ArrayList<String>();// 定义数量集合对象
        while (warehouseProductIterator.hasNext()) {
            WarehouseProduct warehouseProduct = new WarehouseProduct();
            JSONObject jsonObj = (JSONObject) warehouseProductIterator.next();
            String quantity = jsonObj.get("quantity").toString();
            warehouseProduct.setWarehouseId(jsonObj.get("warehouseId").toString());
            warehouseProduct.setProductPriceId(jsonObj.get("productPriceId").toString());
            warehouseProduct.setProductId(jsonObj.get("productId").toString());
            // 判断当前库存中是否存在此商品
            List isExistenceProductList = warehouseProductService.findList(warehouseProduct);
            if (isExistenceProductList != null && isExistenceProductList.size() > 0) {// 如果存在商品则做更新操作
                if (StringUtils.isEmpty(quantity) || "0".equals(quantity)) {
                    continue;
                }
                quantityList.add(quantity);
                WarehouseProduct updateWarehouseProduct = (WarehouseProduct) isExistenceProductList.get(0);
                updateWarehouseProduct.setQuantity((Double.valueOf(updateWarehouseProduct.getQuantity()) + Double.valueOf(quantity)) + "");
                updateWarehouseProductList.add(updateWarehouseProduct);// 将所有需要新增的值装载到集合对象中
            } else {// 否则执行新增操作
                if (StringUtils.isEmpty(quantity)) {
                    quantity = "0";
                }
                warehouseProduct.setQuantity(quantity);
                addWarehouseProductList.add(warehouseProduct);// 将所有需要新增的值装载到集合对象中
            }
        }
        // 执行新增的循环
        for (WarehouseProduct wp : addWarehouseProductList) {
            if (!beanValidator(modelMap, wp)) {
                RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE);
                return null;
            }
            warehouseProductService.save(wp);
            saveStorageRecord(wp, wp.getQuantity());// 执行新增入库单方法
        }
        // 执行修改的循环
        int i = 0;
        for (WarehouseProduct wp : updateWarehouseProductList) {
            String quantityNum = quantityList.get(i);
            warehouseProductService.update(wp);
            saveStorageRecord(wp, quantityNum);// 执行新增入库单方法
        }
        RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
        return null;
    }

    /**
     * 新增入库单方法
     * 
     * @param wp
     *            warehouseProduct
     * @param quantity
     *            新增入库数量
     * @return boolean
     */
    private void saveStorageRecord(WarehouseProduct warehouseProduct, String quantity) {
        SysUser SysUser = UserUtils.getUser();
        // 新增入库单表数据
        Inbound inbound = new Inbound();
        inbound.setDelFlag("0");
        inbound.setWarehouseId(warehouseProduct.getWarehouseId());
        inbound.setManufacturerId("");
        inbound.setInboundTime(new Date());
        if (StringUtils.isNoneBlank(SysUser.getId())) {
            inbound.setOperatorId(SysUser.getId());
        } else {
            inbound.setOperatorId("");
        }
        inboundService.save(inbound);

        // 入库单新增成功之后 新增关联的商品明细表
        InboundProduct inboundProduct = new InboundProduct();
        inboundProduct.setInboundId(inbound.getId());
        inboundProduct.setProductId(warehouseProduct.getProductId());
        inboundProduct.setProductPriceId(warehouseProduct.getProductPriceId());
        inboundProduct.setQuantity(quantity);
        inboundProductSerive.save(inboundProduct);
    }

    /**
     * 商品出库的方法
     * 
     * @param modelMap
     * @param warehouseProduct
     * @return
     * @throws Exception
     */
    @Transactional
    @RequestMapping(value = "/productOutbound", method = RequestMethod.POST)
    @ResponseBody
    public String productOutbound(HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap,
            String ouboundProductPriceS, String warehouseId, String deliveryId, String transportMode, String logisticsCompany, String logisticsBill,
            String contactName, String tel, String remark) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyymmddHHMMSSS");
        if (StringUtils.isEmpty(warehouseId)) {
            modelMap.put("message", "请选择仓库信息！");
            RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE);
            return null;
        }
        if (StringUtils.isEmpty(deliveryId)) {
            modelMap.put("message", "发货单不存在！");
            RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE);
            return null;
        }
        if (StringUtils.isEmpty(transportMode)) {
            modelMap.put("message", "请填写运输方式！");
            RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE);
            return null;
        }
        if (StringUtils.isEmpty(logisticsCompany)) {
            modelMap.put("message", "请填写物流公司！");
            RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE);
            return null;
        }
        if (StringUtils.isEmpty(logisticsBill)) {
            modelMap.put("message", "请填写物流单号！");
            RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE);
            return null;
        }
        if (StringUtils.isEmpty(contactName)) {
            modelMap.put("message", "请填写联系人姓名！");
            RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE);
            return null;
        }
        if (StringUtils.isEmpty(tel)) {
            modelMap.put("message", "请填写联系人电话！");
            RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE);
            return null;
        }

        // 获取当前登陆人对象
        SysUser sysUser = UserUtils.getUser();

        // 根据发货单ID 获取发货单对象和发货单商品数量
        Delivery delivery = deliveryService.findOne(deliveryId);

        // 新增出库单
        Outbound outbound = new Outbound();
        outbound.setDeliveryId(deliveryId);
        outbound.setOrderId(delivery.getOrderId());
        outbound.setWarehouseId(warehouseId);
        outbound.setOutboundTime(new Date());
        outbound.setOutboundCode(sdf.format(new Date()) + ((int) ((Math.random() * 9 + 1) * 1000)));
        outbound.setTel(tel);
        outbound.setContactName(contactName);
        outbound.setLogisticsBill(logisticsBill);
        outbound.setLogisticsCompany(logisticsCompany);
        outbound.setTransportMode(transportMode);
        outbound.setOperatorId(sysUser.getId());
        outboundService.save(outbound);

        ouboundProductPriceS = StringEscapeUtils.unescapeHtml(ouboundProductPriceS);// 去除字符串中的乱码字符
        JSONArray ouboundProductJson = JSON.parseArray(ouboundProductPriceS);// 将字符串转换为JSON对象数组
        Iterator ouboundProductIterator = ouboundProductJson.iterator();
        // 定义发货状态 默认发货完成 2 数量不足时改为1
        int deliveryStatus = 2;
        // 解析json对象数组
        try {
            while (ouboundProductIterator.hasNext()) {
                JSONObject jsonObj = (JSONObject) ouboundProductIterator.next();
                String productId = jsonObj.getString("productId");
                String productPriceId = jsonObj.getString("productPriceId");
                String quantity = jsonObj.getString("quantity");
                // 定义当前商品发货数量
                Double productDeliveryQuantity = 0.0;
                // 定义当前商品已出库数量
                Double productHadDeliveryQuantity = 0.0;

                // 查询当前商品已经出库的数量
                productHadDeliveryQuantity += this.findHadOutboundProductNum(outbound.getOrderId(), deliveryId, productId, productPriceId);
                
                // 查询当前商品在发货单中的发货数量
                try {
                    productDeliveryQuantity = findDeliveryProductNum(deliveryId, productId, productPriceId);
                } catch (Exception e) {
                    modelMap.put("message", "出库失败！");
                    RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE);
                    return null;
                }

                // 根据商品出库数量判断是否已经发货完成
                if (!StringUtils.isEmpty(quantity) && Integer.parseInt(quantity) == 0) { // 判断该条商品是否需要发货
                    continue; 
                } else {// 当商品发货单商品数量大于当前发货数量和已发货数量的时候，当前发货单状态为发货中：1
                    if (productDeliveryQuantity > Double.valueOf(quantity) + productHadDeliveryQuantity) {
                        deliveryStatus = 1;
                    }
                }

                // 出库单创建成功之后创建出库商品信息
                OutboundProduct outboundProduct = new OutboundProduct();
                outboundProduct.setProductId(productId);
                outboundProduct.setOutboundId(outbound.getId());
                outboundProduct.setProductPriceId(productPriceId);
                outboundProduct.setQuantity(quantity);
                outboundProductService.save(outboundProduct);
                // 根据商品ID、价格ID、仓库ID 查询库存信息并执行减库存操作
                WarehouseProduct warehouseProduct = new WarehouseProduct();
                warehouseProduct.setWarehouseId(warehouseId);
                warehouseProduct.setProductId(productId);
                warehouseProduct.setProductPriceId(productPriceId);
                List warehouseProductList = warehouseProductService.findList(warehouseProduct);
                if (null != warehouseProductList && warehouseProductList.size() > 0) {
                    WarehouseProduct wp = (WarehouseProduct) warehouseProductList.get(0);
                    wp.setQuantity((Double.valueOf(wp.getQuantity()) - Double.valueOf(quantity)) + "");
                    warehouseProductService.update(wp);
                } else {
                    modelMap.put("message", "出库失败！");
                    RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE);
                    return null;
                }

            }
            delivery.setStatus(deliveryStatus + "");
            deliveryService.update(delivery);// 保存发货状态
        } catch (Exception e) {
            throw new RuntimeException("保存失败");
        }
        modelMap.put("message", "出库成功！");
        RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
        return null;
    }
    
    /**
     * 查询当前商品已经出库的数量
     * 
     * @param orderId
     * @param deliveryId
     * @param productId
     * @param productPriceId
     * @return
     */
    private double findHadOutboundProductNum(String orderId, String deliveryId, String productId, String productPriceId){
        double productHadDeliveryQuantity = 0.0;
        Outbound queryOutbound = new Outbound();
        queryOutbound.setOrderId(orderId);
        queryOutbound.setDeliveryId(deliveryId);
        List<Outbound> outboundList = outboundService.findAll(queryOutbound);
        for (Outbound outbound1 : outboundList) {
            OutboundProduct queryOutboundProduct = new OutboundProduct();
            queryOutboundProduct.setOutboundId(outbound1.getId());
            queryOutboundProduct.setProductId(productId);
            queryOutboundProduct.setProductPriceId(productPriceId);
            List<OutboundProduct> outBoundProduct = outboundProductService.findAll(queryOutboundProduct);
            for (OutboundProduct outboundProduct2 : outBoundProduct) {
                productHadDeliveryQuantity += Double.valueOf(outboundProduct2.getQuantity());
            }
        }
        return productHadDeliveryQuantity;
    }
    
    /**
     * 查询当前商品在发货单中的数量
     * @param deliveryId
     * @param productId
     * @param productPriceId
     * @return
     * @throws Exception 
     */
    private double findDeliveryProductNum(String deliveryId, String productId, String productPriceId) throws Exception{
        double productDeliveryQuantity = 0.0;
        DeliveryProduct queryDeliveryProduct = new DeliveryProduct();
        queryDeliveryProduct.setDeliveryId(deliveryId);
        queryDeliveryProduct.setProductId(productId);
        queryDeliveryProduct.setProductPriceId(productPriceId);
        List<DeliveryProduct> deliveryProduct = deliveryProductService.findAll(queryDeliveryProduct);
        if (null != deliveryProduct && deliveryProduct.size() > 0) {
            productDeliveryQuantity = Double.valueOf(deliveryProduct.get(0).getQuantity());
        }else{
            throw new Exception("发货单中不包含该商品");
        }
        return productDeliveryQuantity;
    }

    /**
     * 保存修改的数据
     * 
     * @param modelMap
     * @param warehouseProduct
     * @return
     * @throws Exception
     */
    // @RequiresPermissions("warehouse:warehouseProduct:update")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public String update(HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap,
            WarehouseProduct warehouseProduct) throws Exception {
        if (!beanValidator(modelMap, warehouseProduct)) {
            RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE);
            return null;
        }
        warehouseProductService.update(warehouseProduct);
        RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
        return null;
    }

    /**
     * 删除数据库
     * 
     * @param modelMap
     * @param warehouseProductId
     * @return
     * @throws Exception
     */
    // @RequiresPermissions("warehouse:warehouseProduct:delete")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public String delete(HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap, String id)
            throws Exception {
        List<String> listId = Arrays.asList(id.split(","));
        warehouseProductService.delete(listId);
        RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
        return null;
    }

    /**
     * 假删除
     * 
     * @param modelMap
     * @param warehouseProduct
     * @return
     * @throws Exception
     */
    // @RequiresPermissions("warehouse:warehouseProduct:delete")
    @RequestMapping(value = "/remove", method = RequestMethod.POST)
    @ResponseBody
    public String remove(HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap,
            WarehouseProduct warehouseProduct) throws Exception {
        warehouseProductService.remove(warehouseProduct);
        RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
        return null;
    }

    /**
     * 导出Excel数据
     * 
     * @param modelMap
     * @param warehouseProduct
     * @return
     * @throws Exception
     */
    // @RequiresPermissions("warehouse:warehouseProduct:export")
    @RequestMapping(value = "/export")
    public String export(HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap,
            WarehouseProduct warehouseProduct) throws Exception {
        String fileName = DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
        List<WarehouseProduct> warehouseProductList = warehouseProductService.findAll(warehouseProduct);
        new ExportExcel(null, WarehouseProduct.class).setDataList(warehouseProductList).write(response, fileName).dispose();
        return null;
    }
}